package server;

import client.CreateGameFrame;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author hxl851
 */
public class Server {

    public static final int PORT = 8888;
    private ServerSocket serverSocket;
    private Socket clientSocket1, clientSocket2;
    private CreateGameFrame createGameFrame;

    public Server(CreateGameFrame createGameFrame) throws IOException {
        this.createGameFrame = createGameFrame;
        serverSocket = new ServerSocket(PORT);
        Thread connectionThread = new Thread(new Connection());
        connectionThread.start();
    }

    public void gameBegin() throws IOException {
        GameLogic gameLogic = new GameLogic(clientSocket1, clientSocket2);
        gameLogic.gameBegin();
    }

    //Thread which is used to wait for clients to connect to this server
    class Connection implements Runnable {

        public void run() {
            try {
                clientSocket1 = serverSocket.accept();
                clientSocket2 = serverSocket.accept();
                createGameFrame.setStatus();
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(createGameFrame, "Something wrong with Network.");
                System.exit(1);
            }
        }
    }
}
